package com.yq.ylmall.common.log.aspect;

import com.yq.ylmall.common.log.annotation.Log;
import com.yq.ylmall.common.log.service.AsyncOperLogService;
import com.yq.ylmall.common.log.utils.LogUtil;
import com.yq.ylmall.common.utils.AuthContextUtil;
import com.yq.ylmall.model.log.SysOperLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component//表示此类交给spring容器管理
@Aspect//表示是一个切面类
@Slf4j//日志
public class LogAspect {
    @Autowired
    private AsyncOperLogService asyncOperLogService;
    //环绕通知
    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, Log sysLog){
//        业务方法调用之前，封装数据
        SysOperLog sysOperLog = new SysOperLog();
        System.out.println(AuthContextUtil.get().getUsername());
        System.out.println("ok");
        LogUtil.beforeHandleLog(sysLog,joinPoint,sysOperLog);
        log.info("=====================方法调用开始==============================");
        log.info("模块名称:{}",sysLog.title());
        //调用业务方法
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            //业务方法调用之后，封装数据
            LogUtil.afterHandlLog(sysLog,proceed,sysOperLog,0,null);
            log.info("请求的方法:{}",sysOperLog.getRequestMethod());
            log.info("操作人员:{}",sysOperLog.getOperName());
            log.info("主机地址:{}",sysOperLog.getOperIp());
            log.info("请求参数:{}",sysOperLog.getOperParam());
            log.info("返回参数:{}",sysOperLog.getJsonResult());
            log.info("==========================方法调用结束======================");
        } catch (Throwable e) {
            e.printStackTrace();
            LogUtil.afterHandlLog(sysLog,proceed,sysOperLog,1,e.getMessage());
            throw new RuntimeException();
        }
        //调用service方法把日志信息添加数据库里面
        asyncOperLogService.saveSysOperLog(sysOperLog);
        return proceed;
    }
}
